package com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.SelectAgentAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.SnlistAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.MySelectAgentBean;
import com.laiyima.zhongjiang.linghuilv.demo.bean.SnListBean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
  * create an instance of this fragment.
 */
public class IntervalAllocationFragment extends Fragment implements View.OnClickListener,ListViewPlus.ListViewPlusListener {
    private String TAG="IntervalAllocationFragment";
    private int iaCode;

    private LinearLayout show_toinputsn,ia_liner;
    private EditText inputStart,inputEnd;
    private TextView show_number_sn;
    private Button show_toSnliat,ia_select_button;
    private int count,page_count,page_index;

    private LinearLayout mycheckBox;
    private int cb=1;
    private String select_sn="";
    private int selectCode=0;

    private ListViewPlus mListView;
    private SnListBean mSnListBean;
    private SnlistAdapter mSnlistAdapter;
    private List<SnListBean> SnListBeanListBean = new ArrayList<>();

    private ImageView all;
    @Override
    public void onRefresh() {

        mSnlistAdapter.notifyDataSetChanged();

        loadData(ListViewPlus.REFRESH);
        // Log.e(TAG, "onRefresh:");

    }

    @Override
    public void onLoadMore() {
        if(page_index<page_count){
             Log.e(TAG, "page_index:"+page_index);
            loadData(ListViewPlus.LOAD);
        }else{
            Toast.makeText(getContext().getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
            onLoadComplete();
        }
    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {

                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:

                    Log.e(TAG, "onRefresh:");
                    //intView();
                    onLoadComplete();
                    Toast.makeText(getContext().getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    page_index++;
                    Log.e(TAG, "onLoadMore:");
                    loadMode(page_index);
                    break;
            }

        }

    };

    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }
    private void loadMode(int page_index) {
        String start_sn=inputStart.getText().toString();
        String end_sn=inputEnd.getText().toString();
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/select_transfer");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("page_index", page_index);
        params.addBodyParameter("start", start_sn);
        params.addBodyParameter("end", end_sn);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    iaCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String sn = value.getString("sn");
                        mSnListBean = new SnListBean(sn);
                        SnListBeanListBean.add(mSnListBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.e(TAG, "回调成功" + result);
                if (iaCode == 200) {
                   // mSnlistAdapter = new SnlistAdapter(getContext().getApplicationContext(), SnListBeanListBean);
                    mSnlistAdapter.notifyDataSetChanged();
                   // mListView.setAdapter(mSnlistAdapter);
                }

                if (iaCode == 500) {
                    Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "系统异常");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished(){}
        });

    }
    @Override
    public void onPause() {
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE); //私有数据
        SharedPreferences.Editor editor = sharedPreferences.edit();
        String  start_sn=inputStart.getText().toString();
        String end_sn = inputEnd.getText().toString();
        editor.putString("start_sn", start_sn );
        editor.putString("end_sn", end_sn );
        editor.commit();
        super.onPause();
    }

   private Handler mHandler;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.fragment_interval_allocation, container, false);
        show_toinputsn=view.findViewById(R.id.show_toinputsn);
        inputStart=view.findViewById(R.id.start_sn);
        inputEnd=view.findViewById(R.id.end_sn);
        show_number_sn=view.findViewById(R.id.show_number_sn);
        show_toSnliat=view.findViewById(R.id.to_list_sn);
        show_toSnliat.setOnClickListener(this);
        ia_liner=view.findViewById(R.id.ia_liner);
        mListView= (ListViewPlus) view.findViewById(R.id.ia_sn_list);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);
        SharedPreferences sharedPreferences = getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String start_sn = sharedPreferences.getString("start_sn", "");
        inputStart.setText(start_sn);
        String end_sn = sharedPreferences.getString("end_sn", "");
        inputEnd.setText(end_sn);
        mycheckBox=view.findViewById(R.id.ia_SelectivecheckBox);
        mycheckBox.setOnClickListener(this);
        all=view.findViewById(R.id.ia_allselect_image);
        all.setOnClickListener(this);


        ia_select_button=view.findViewById(R.id.ia_select_button);
        ia_select_button.setOnClickListener(this);
        setListener();
        return view;
    }




    private void setListener() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListViewPlus listView=(ListViewPlus)parent;
                SnListBean mSnListBean=(SnListBean)listView.getItemAtPosition(position);
                String sn=mSnListBean.getSn();
                if(mSnListBean.isChecked()){
                    select_sn=select_sn.replace(sn,"");
                    selectCode=selectCode-1;
                    Log.e(TAG, "true" );
                    mSnListBean.setChecked(false);

                }else{
                    selectCode=selectCode+1;
                    select_sn=","+sn+select_sn;
                    Log.e(TAG, "false" );
                    mSnListBean.setChecked(true);
                }
                show_number_sn.setText(selectCode+"/"+count);
                mSnlistAdapter.notifyDataSetChanged();
            }
        });

    }
    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.to_list_sn:
                showList();
                break;
            case R.id.ia_SelectivecheckBox:
                if(cb==1){
                    all.setImageResource(R.drawable.cb_true);
                    cb=2;
                    selectCode=1;
                    for (int i = 0; i < SnListBeanListBean.size(); i++) {
                        select_sn=","+SnListBeanListBean.get(i).getSn()+select_sn;

                        SnListBeanListBean.get(i).setChecked(true);
                    }
                }else {
                    all.setImageResource(R.drawable.cb_fase);
                    cb=1;
                    selectCode=0;
                    for(int i = 0; i < SnListBeanListBean.size(); i++){
                        SnListBeanListBean.get(i).setChecked(false);
                    }
                }
                mSnlistAdapter.notifyDataSetChanged();
                break;
            case R.id.ia_allselect_image:
                if(cb==1){
                    all.setImageResource(R.drawable.cb_true);
                    cb=2;
                    selectCode=1;
                    for (int i = 0; i < SnListBeanListBean.size(); i++) {
                        select_sn=","+SnListBeanListBean.get(i).getSn()+select_sn;

                        SnListBeanListBean.get(i).setChecked(true);
                        show_number_sn.setText(SnListBeanListBean.size()+"/"+count);
                    }
                }else {
                    show_number_sn.setText(0+"/"+count);
                    all.setImageResource(R.drawable.cb_fase);
                    cb=1;
                    selectCode=0;
                    for(int i = 0; i < SnListBeanListBean.size(); i++){
                        SnListBeanListBean.get(i).setChecked(false);
                    }
                }
                mSnlistAdapter.notifyDataSetChanged();
                break;
            case R.id.ia_select_button:
                dialog_show();
                break;
        }
    }

    private void showList() {
        String start_sn=inputStart.getText().toString();
        if(start_sn.length()>0) {
            String end_sn = inputEnd.getText().toString();
            SharedPreferences sharedPreferences = getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
            String userID = sharedPreferences.getString("userID", "");
            RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/section_transfer");
            //需要带入的参数
            params.addBodyParameter("uid", userID);
            params.addBodyParameter("start", start_sn);
            params.addBodyParameter("end", end_sn);

            // params.addBodyParameter("captcha", captcha);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        iaCode = jsonObject.optInt("code", 0);
                        String data = jsonObject.optString("data", null);
                        if (!TextUtils.isEmpty(data)) {
                            JSONObject jsonObjec = new JSONObject(data);
                            count = jsonObjec.optInt("count", 0);
                            show_number_sn.setText(0+"/"+count);
                            page_count = jsonObjec.optInt("page_count", 0);
                            page_index = jsonObjec.optInt("page_index", 0);
                        }
                        JSONObject jData = new JSONObject(data);
                        JSONArray list = jData.getJSONArray("list");
                        for (int i = 0; i < list.length(); i++) {
                            JSONObject value = list.getJSONObject(i);
                            String sn = value.getString("sn");
                            mSnListBean = new SnListBean(sn);
                            SnListBeanListBean.add(mSnListBean);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Log.e(TAG, "回调成功" + result);
                    if (iaCode == 200) {
                        if (SnListBeanListBean.size() == 0) {
                            Toast.makeText(getContext().getApplicationContext(), "该区间暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            show_toinputsn.setVisibility(View.GONE);
                            ia_liner.setVisibility(View.VISIBLE);
                        }
                    }
                    if (iaCode == 500) {
                        Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "系统异常");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Log.e(TAG, "回调失败");
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    if (iaCode == 200) {
                        mSnlistAdapter = new SnlistAdapter(getContext().getApplicationContext(), SnListBeanListBean);
                        mSnlistAdapter.notifyDataSetChanged();
                        mListView.setAdapter(mSnlistAdapter);
                    }

                }
            });
        }
    }

    private void dialog_show() {
        IntervalAllocationFragment.CustomPopup customPopup = new IntervalAllocationFragment.CustomPopup(getContext());
        new XPopup.Builder(getContext())
                .asCustom(customPopup)
                .show();

    }
    public  class CustomPopup extends CenterPopupView {
        private MySelectAgentBean mMySelectAgentBean;
        private SelectAgentAdapter mSelectAgentAdapter;
        private ListView listView;
        private List<MySelectAgentBean> MySelectAgentBeanBean = new ArrayList<>();
        private TextView textView;
        private String agentUid="a";
        private EditText editText;
        public CustomPopup(@NonNull Context context) {
            super(context);
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.custom_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            textView=findViewById(R.id.yingchanglin);
            listView=findViewById(R.id.show_select_name);
            editText=findViewById(R.id.select_agent_list);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ListView listView=(ListView)parent;
                    MySelectAgentBean mTaxbean=(MySelectAgentBean)listView.getItemAtPosition(position);
                    String admin_name=mTaxbean.getAdmin_name();
                    editText.setText(admin_name);
                    agentUid=mTaxbean.getUid().toString();
                    textView.setVisibility(VISIBLE);
                    listView.setVisibility(GONE);
                }
            });
            findViewById(R.id.select_agent_button).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(selectCode==0){
                        Toast.makeText(getContext().getApplicationContext(), "请选要划拨的号", Toast.LENGTH_SHORT).show();
                    }else{
                        if(agentUid.equals("a")) {
                            Toast.makeText(getContext().getApplicationContext(), "请选择划拨的服务商", Toast.LENGTH_SHORT).show();
                        }else{

                            RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/upload");
                            params.addBodyParameter("uid", agentUid);
                            params.addBodyParameter("sn", select_sn);

                            x.http().post(params, new Callback.CommonCallback<String>() {
                                @Override
                                public void onSuccess(String result) {
                                    if (iaCode == 200) {
                                        Toast.makeText(getContext().getApplicationContext(), "划拨成功", Toast.LENGTH_SHORT).show();
                                        dismiss();
                                        mSnlistAdapter.notifyDataSetChanged();
                                        select_sn="";
                                        selectCode=0;
                                        all.setImageResource(R.drawable.cb_fase);
                                        cb=1;
                                    }
                                    if (iaCode == 500) {

                                    }
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    Log.e(TAG, "回调失败");
                                }
                                @Override
                                public void onCancelled(CancelledException cex) {
                                }
                                @Override
                                public void onFinished() {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Message msg = handler1.obtainMessage();
                                            msg.what = 20;
                                            handler1.sendMessage(msg);
                                        }
                                    }).start();

                                }
                            });

                        }
                    }
                }
            });
            findViewById(R.id.select_agent_list).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    listView.setVisibility(VISIBLE);
                    textView.setVisibility(GONE);
                    intGetName();
                }
            });

            findViewById(R.id.tv_close).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }

        protected void onShow() {
            super.onShow();
        }
        public void intGetName(){
            if(MySelectAgentBeanBean.size()!=0){
                MySelectAgentBeanBean.clear();
            }
            SharedPreferences sharedPreferences = getContext().getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
            String userID = sharedPreferences.getString("userID", "");
            RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/agent_transfer");
            params.addBodyParameter("uid", userID);

            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        iaCode = jsonObject.optInt("code", 0);
                        String data = jsonObject.optString("data", null);
                        JSONObject jData = new JSONObject(data);
                        JSONArray list = jData.getJSONArray("list");
                        for (int i = 0; i < list.length(); i++) {
                            JSONObject value = list.getJSONObject(i);
                            String admin_name = value.getString("admin_name");
                            String uid = value.getString("uid");
                            mMySelectAgentBean = new MySelectAgentBean(uid,admin_name);
                            MySelectAgentBeanBean.add(mMySelectAgentBean);
                            mSelectAgentAdapter = new SelectAgentAdapter(getContext().getApplicationContext(),MySelectAgentBeanBean);
                            listView.setAdapter(mSelectAgentAdapter);

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (iaCode == 200) {
                    }
                    if (iaCode == 500) {
                        Toast.makeText(getContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "系统异常");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Log.e(TAG, "回调失败");
                }
                @Override
                public void onCancelled(CancelledException cex) {
                }
                @Override
                public void onFinished() {
                }
            });
        }
    }

    Handler handler1 = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 20:
                    SnListBeanListBean.clear();
                    showList();
                    Log.e(TAG, "刷新");
            }
        }
    };


}
